package com.owulia.leetcode.num.linked.list;

public class MergeTwoList {
    public static ListNode mergeTwoLists(ListNode list1, ListNode list2) {
        if (list1 == null) {
            return list2;
        }
        if (list2 == null) {
            return list1;
        }
        ListNode ans = null;
        if (list1.val < list2.val) {
            ans = list1;
            list1 = list1.next;
        } else {
            ans = list2;
            list2 = list2.next;
        }
        ListNode tail = ans;
        while (list1 != null || list2 != null) {
            if (list1 == null) {
                tail.next = list2;
                break;
            } else if (list2 == null) {
                tail.next = list1;
                break;
            } else {
                if (list1.val < list2.val) {
                    tail.next = list1;
                    list1 = list1.next;
                } else {
                    tail.next = list2;
                    list2 = list2.next;
                }
                tail = tail.next;
            }
        }
        return ans;
    }


    public static void main(String[] args) {
        ListNode head = new ListNode(1);
        head.next = new ListNode(2);
        head.next.next = new ListNode(3);
        head.next.next.next = new ListNode(4);

        ListNode head2 = new ListNode(2);
        head2.next = new ListNode(3);
        head2.next.next = new ListNode(4);
        head2.next.next.next = new ListNode(5);
        ListNode newHead = mergeTwoLists(head, head2);
        do {
            System.out.printf("\t" + newHead.val);
            newHead = newHead.next;
        } while (null != newHead.next);
        System.out.printf("\t" + newHead.val);
    }
}
